﻿using System;

namespace WPFNote.Utilities.Http {
    public class HttpDataHelper {
        /// <summary>
        /// 实体类转换成？格式的参数，
        /// {id:1,title="aaa"} ==> ?id=1&title=aaa
        /// </summary>
        /// <param name="t"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static string GetParam<T>(T t) {
            var param = "";
            var type = t.GetType();
            foreach (var item in type.GetProperties())
            {
                var name = item.Name;
                var value = item.GetValue(t, null);
                if (value != null) {
                    if (item.PropertyType.IsGenericType &&
                        item.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        var typeArray = item.PropertyType.GetGenericArguments();
                        var baseType = typeArray[0];
                        if (baseType.IsEnum) {
                            var enumValue = Enum.Parse(item.PropertyType.GetGenericArguments()[0], value.ToString());
                            value = (int)enumValue;
                        } 
                    }
                    if (item.PropertyType.IsEnum) {
                        var enumValue = Enum.Parse(item.PropertyType.GetGenericArguments()[0], value.ToString());
                        value = (int)enumValue;
                    } 
                    param += $"{(!string.IsNullOrWhiteSpace(param) ? "&" : "")}{name}={value}";
                }
            }
            return string.IsNullOrWhiteSpace(param) ? "" : $"?{param}";
        }
    }
}